package com.linln.modules.wtpshop.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linln.common.enums.ServiceTypeEnum;
import com.linln.common.utils.DistanceUtil;
import com.linln.modules.area.service.AreaService;
import com.linln.modules.shopsService.domain.Shops;
import com.linln.modules.shopsService.repository.ShopsRepository;
import com.linln.modules.shopsService.service.ShopsService;
import com.linln.modules.wtpshop.repository.ShopMapper;
import com.linln.modules.wtpshop.service.ShopService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author zsc
 * @date 2020/11/19
 */
@Service("shopService")
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopMapper shopsMapper;

    @Autowired
    private ShopsRepository shopsRepository;

    @Autowired
    private AreaService areaService;


    //获取附近五家店铺
    @Override
    public Map<String, Object> getFiveNearbyShops(String lon, String lat) {
        Map<String, Object> map = new HashMap<>();
        startLimit(0, 5);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo(shopsMapper.getNearbyShops(lon, lat, null, null, null));
        map.put("data", setDistance(lon, lat, pageInfo));
        map.put("code", 200);
        return map;
    }

    /**
     * 获取附近店铺
     *
     * @param lon 经度
     * @param lat 纬度
     * @return 店铺列表
     */
    @Override
    public Map<String, Object> getNearbyShops(String lon, String lat, int pageNum, int limit, Integer areaId, Integer shopType, Integer reserve) {
        Map<String, Object> map = new HashMap<>();
        List<Integer> areaIds = areaService.getSonIds(areaId);
        startLimit(pageNum, limit);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(shopsMapper.getNearbyShops(lon, lat, areaIds, shopType, reserve));
        map.put("data", setDistance(lon, lat, pageInfo));
        map.put("total", pageInfo.getTotal());
        map.put("code", 200);
        return map;
    }

    /**
     * 根据店铺评分排序 高的在前
     *
     * @return 店铺列表
     */
    @Override
    public Map<String, Object> getShopOrderScore(String lon, String lat, int pageNum, int limit, Integer areaId, Integer shopType, Integer reserve) {
        Map<String, Object> map = new HashMap<>();
        List<Integer> areaIds = areaService.getSonIds(areaId);
        startLimit(pageNum, limit);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(shopsMapper.getShopOrderScore(areaIds, shopType, reserve));
        map.put("data", setDistance(lon, lat, pageInfo));
        map.put("total", pageInfo.getTotal());
        map.put("code", 200);
        return map;
    }

    /**
     * 根据店铺销量排序 高的在前
     *
     * @return 店铺列表
     */
    @Override
    public Map<String, Object> getShopsByShopType(String lon, String lat, int pageNum, int limit, Integer areaId, Integer shopType) {
        Map<String, Object> map = new HashMap<>();
        List<Integer> areaIds = areaService.getSonIds(areaId);
        startLimit(pageNum, limit);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(shopsMapper.getShopsByShopType(areaIds, shopType));
        map.put("data", setDistance(lon, lat, pageInfo));
        map.put("total", pageInfo.getTotal());
        map.put("code", 200);
        return map;
    }


    //通过店铺名称搜索
    @Override
    public Map<String, Object> getShopsByShopName(String lon, String lat, int pageNum, int limit, Integer areaId, String shopName) {
        Map<String, Object> map = new HashMap<>();
        List<Integer> areaIds = areaService.getSonIds(areaId);
        startLimit(pageNum, limit);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(shopsMapper.getShopsByShopName(areaIds, shopName));
        map.put("data", setDistance(lon, lat, pageInfo));
        map.put("total", pageInfo.getTotal());
        map.put("code", 200);
        return map;
    }

    @Value("${server.ip}")
    private String ip;

    /**
     * @param lon
     * @param lat
     * @return
     */
    private List<Map<String, Object>> setDistance(String lon, String lat, PageInfo<Map<String, Object>> pageInfo) {
        List<Map<String, Object>> content = pageInfo.getList();
        List<Map<String, Object>> shopMap = new ArrayList<>();
        //设置距离
        boolean flag = false;
        if (!("0".equals(lon) || "0".equals(lat))) {
            flag = true;
        }
        boolean finalFlag = flag;
        content.forEach(item -> {
                    Map<String, Object> map = new HashMap<>(item);
                    if (finalFlag) {
                        double distance;
                        if (Strings.isBlank((String) map.get("latitude")) || Strings.isBlank((String) map.get("longitude"))) {
                            distance = 0;
                        } else {
                            distance = DistanceUtil.distance(Double.parseDouble(lon), Double.parseDouble(lat), Double.parseDouble((String) map.get("longitude")), Double.parseDouble((String) map.get("latitude")));
                        }
                        map.put("distance", String.valueOf(distance));
                    } else {
                        map.put("distance", String.valueOf(0));
                    }

                    map.put("shop_picture", ip + map.get("shop_picture"));
                    String[] shopTypeId = ((String) item.get("shop_type")).split(",");
                    map.put("shop_type_list", shopsMapper.selectShopServiceTypeName(shopTypeId));
                    map.putIfAbsent("score", 0.0);
                    shopMap.add(map);
                }
        );

        return shopMap;
    }


    //通过店铺id获取店铺的所有类型名称
    @Override
    public List<Map<String, String>> selectShopServiceType(String[] shopTypes) {
        List<Map<String, String>> mapList = new ArrayList<>();
        List<String> strings = shopsMapper.selectShopServiceTypeId(shopTypes);
        strings.forEach(item -> {
            Map<String, String> map = new HashMap<>();
            map.put("shopTypeId", item);
            switch (item) {
                case ServiceTypeEnum.WASH: {
                    map.put("imgAddr", ip + "images/xiche.png");
                    break;
                }
                case ServiceTypeEnum.REPAIR: {
                    map.put("imgAddr", ip + "images/weixiu.png");
                    break;
                }
                case ServiceTypeEnum.TESTING: {
                    map.put("imgAddr", ip + "images/jianche.png");
                    break;
                }
                case ServiceTypeEnum.YEARRWVIEW: {
                    map.put("imgAddr", ip + "images/nianshen.png");
                    break;
                }
            }
            mapList.add(map);
        });
        return mapList;
    }


    @Override
    public boolean updateShopAddress(Shops shop, long userId) {
//        shop.setShopId(shopsRepository.byUsersearchShopId(userId));
        return shopsMapper.updateShopAddress(shop);
    }

    @Override
    public boolean updateOpeningStatus(String shopId, Integer status) {
        return shopsMapper.updateOpeningStatus(shopId, status);
    }

    @Override
    public boolean updateShopScore(String shopId, Double score) {
        return shopsMapper.updateShopScore(shopId, score);
    }


    /**
     * 开启分页
     *
     * @param pageNum
     * @param limit
     */
    private void startLimit(Integer pageNum, Integer limit) {
        PageHelper.startPage(pageNum + 1, limit);
    }
}
